<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\common\Amap;
use app\common\GptService;
use app\common\Pay;
use app\common\UsersService;
use app\job\Task;
use app\model\Config;
use app\model\Talent;
use app\model\TalentAssess;
use app\model\TalentAssessTip;
use app\model\TalentAssessTipClass;
use app\model\TalentComment;
use app\model\TalentData;
use app\model\TalentDataClass;
use app\model\TalentDataDetail;
use app\model\TalentDocument;
use app\model\TalentGoods;
use app\model\TalentGoodsOrders;
use app\model\TalentGoodsOrdersRenew;
use app\model\TalentSchool;
use app\model\TalentSchoolClass;
use app\model\TalentSchoolCompress;
use app\model\TalentSchoolMajor;
use app\model\TalentSchoolRank;
use app\model\UsersRelated;
use app\model\UsersShield;
use app\Request;
use think\db\Query;
use think\Exception;
use think\facade\Db;
use think\facade\Queue;
use think\response\Json;

class TalentController extends BaseController
{
	protected array $middleware = ['Login' => [
		'except' => ['index', 'talent_goods', 'test', 'assess', 'tip', 'data_sort',
			'get_config', 'major', 'compress', 'year', 'ranking', 'ranking_detail', 'talent_rule', 'read', 'comment_list'],
	]];
	
	/**
	 * 屏蔽
	 * @param Request $request
	 * @return void
	 */
	function shield(Request $request)
	{
		$id = $request->post('id/d');
		UsersShield::create([
			'users_id'=>$request->users_id,
			'pro_id'=>$id,
			'type'=>'talent'
		]);
		writeJson();
	}
	
	/**
	 * 人才引进-列表
	 * @param int $type
	 * @param string $keyword
	 * @return Json
	 */
	public function index(Request $request,int $type, string $keyword)
	{
		$shield = UsersShield::where(['users_id'=>$request->users_id,'type'=>'talent'])->column('pro_id');
		
		$rows = Talent::with(['users'])
			->where(['type' => $type])
			->when(!empty($keyword), function (Query $query) use ($keyword) {
				$query->whereLike('title|content', '%' . $keyword . '%');
			})
			->whereNotIn('id',$shield)
			->order(['id' => 'desc'])
			->paginate()
			->items();
		writeJson($rows);
	}
	
	/**
	 * 人才引进-发布
	 * @param Request $request
	 * @return Json
	 */
	public function save(Request $request)
	{
		$params = $request->param();
		Talent::create($params);
		writeJson();
	}
	
	/**
	 * 人才引进-详情
	 * @param int $id
	 * @param Request $request
	 * @return Json
	 */
	public function read(int $id, Request $request)
	{
		$row = Talent::with([
			'users',
			'users_collect' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'talent']);
			},
			'users_like' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'talent']);
			}])->find($id);
		event('TalentIncBrowse', $id); //增加浏览数量
		UsersService::footmark($id, $request->users_id, 'talent');
		
		writeJson($row);
	}
	
	/**
	 * 评论
	 * @param Request $request
	 * @return Json
	 */
	function comment(Request $request): Json
	{
		$params = $request->param();
		$ip = $request->ip();
		$params['ip'] = $ip;
		$ip = Amap::ip($ip);
		$ip = json_decode($ip);
		if ($ip->status == 1) {
			$params['city'] = $ip->province;
		} else {
			$params['city'] = '未知';
		}
		$res = TalentComment::create($params);
		foreach ($params['content'] as $v) {
			if ($v['type'] == 'at') {
				//@提醒  提醒接收人
				UsersRelated::create(['users_id' => $v['userId'], 'type' => 8, 'from_users_id' => $request->users_id, 'scene' => 'Talent', 'pro_id' => $res->id]);
			}
		}
		if (!empty($params['to_users_id'])) {
			//回复提醒  提醒接收人
			UsersRelated::create(['users_id' => $params['to_users_id'], 'type' => 1, 'from_users_id' => $request->users_id, 'scene' => 'Talent', 'pro_id' => $res->id]);
		} else {
			//评论提醒  提醒发布人
			$pro = Talent::find($params['talent_id']);
			UsersRelated::create(['users_id' => $pro->users_id, 'type' => 2, 'from_users_id' => $request->users_id, 'scene' => 'Talent', 'pro_id' => $res->id]);
		}
		event('TalentIncComment', $params['talent_id']); //增加评论数量
		$row = TalentComment::with(['users', 'to_users', 'users_like' => function (Query $query) use ($request) {
			$query->where(['users_id' => $request->users_id, 'type' => 'talent_comment']);
		}])->find($res->id);
		writeJson($row);
	}
	
	/**
	 * 评论列表
	 * @param int $talent_id
	 * @param mixed $comment_id
	 * @param Request $request
	 * @return Json
	 */
	function comment_list(int $talent_id, mixed $comment_id, Request $request)
	{
		$top_id = 0;
		if (!empty($comment_id)) {
			$row = TalentComment::find($comment_id);
			if ($row->pid == 0) {
				//顶级评论 放在第一条
				$top_id = $row->id;
			} else {
				//子评论 找出顶级评论
				$row = TalentComment::find($row->pid);
				$top_id = $row->id;
			}
		}
		
		$rows = TalentComment::where(['pid' => 0, 'talent_id' => $talent_id])
			->withCount('comment')
			->with([
				'users',
				'comment' => function (Query $query) use ($request, $comment_id) {
					$query
						->with(['users', 'to_users', 'users_like' => function (Query $query) use ($request) {
							$query->where(['users_id' => $request->users_id, 'type' => 'talent_comment']);
						}])
						->when(!empty($comment_id), function (Query $query) use ($comment_id) {
							$query->field("*,IF(id = $comment_id,1,0) AS top")->order(['top' => 'desc', 'id' => 'desc']);
						}, function (Query $query) {
							$query->order(['id' => 'desc']);
						})
						->limit($this->comment_list_rows);
				},
				'users_like' => function (Query $query) use ($request) {
					$query->where(['users_id' => $request->users_id, 'type' => 'talent_comment']);
				}])
			->when(!empty($comment_id), function (Query $query) use ($top_id) {
				$query->field("IF(id = $top_id,1,0) AS top")->order(['top' => 'desc', 'id' => 'desc']);
			}, function (Query $query) {
				$query->order(['id' => 'desc']);
			})
			->paginate()
			->items();
		writeJson($rows);
	}
	
	/**
	 * 评论详情
	 * @param int $id
	 * @param mixed $comment_id
	 * @param Request $request
	 * @return Json
	 */
	function comment_detail(int $id, mixed $comment_id, Request $request): Json
	{
		$child = false;
		if (!empty($comment_id)) {
			$row = TalentComment::find($comment_id);
			if ($row->pid != 0) {
				//二级评论
				$child = true;
			}
		}
		$rows = TalentComment::where(['pid' => $id])
			->with(['users', 'to_users', 'users_like' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'talent_comment']);
			}])
			->when($child, function (Query $query) use ($comment_id) {
				$query->where('id', '<>', $comment_id);
			})
			->order(['id' => 'desc'])
			->paginate($this->comment_detail_rows)
			->items();
		
		writeJson($rows);
	}
	
	/**
	 * 评论点赞
	 * @param Request $request
	 * @return Json
	 */
	function comment_like(Request $request)
	{
		$id = $request->param('id');
		$res = UsersService::like($id, $request->users_id, 'talent_comment');
		$res ? event('TalentCommentIncLike', $id) : event('TalentCommentDecLike', $id); //增加/减少  点赞数量
		if ($res) {
			$pro = TalentComment::find($id);
			UsersRelated::create(['users_id' => $pro->users_id, 'type' => 4, 'from_users_id' => $request->users_id, 'scene' => 'Talent', 'pro_id' => $id]);
		}
		writeJson($res);
	}
	
	
	/**
	 * 收藏
	 * @param Request $request
	 * @return void
	 */
	function collect(Request $request)
	{
		$id = $request->param('id');
		$res = UsersService::collect($id, $request->users_id, 'talent');
		$res ? event('TalentIncCollect', $id) : event('TalentDecCollect', $id); //增加/减少  收藏数量
		if ($res) {
			$pro = Talent::find($id);
			UsersRelated::create(['users_id' => $pro->users_id, 'type' => 7, 'from_users_id' => $request->users_id, 'scene' => 'Talent', 'pro_id' => $id]);
		}
		writeJson($res);
	}
	
	/**
	 * 点赞
	 * @param Request $request
	 * @return void
	 */
	function like(Request $request)
	{
		$id = $request->post('id');
		$res = UsersService::like($id, $request->users_id, 'talent');
		$res ? event('TalentIncLike', $id) : event('TalentDecLike', $id); //增加/减少  点赞数量
		if ($res) {
			$pro = Talent::find($id);
			UsersRelated::create(['users_id' => $pro->users_id, 'type' => 3, 'from_users_id' => $request->users_id, 'scene' => 'Talent', 'pro_id' => $id]);
		}
		writeJson($res);
	}
	
	
	/**
	 * 人才引进-AI写文案
	 * @return Json
	 */
	function ai_notes(Request $request)
	{
		$params = $request->param(); //type
		try {
			GptService::decGptNum($request->users_id, 1, "AI写文案" . date('Y-m-d H:i:s'));
		} catch (Exception $e) {
			writeJson(0, $e->getMessage());
		}
		$params['name'] = date('Y-m-d H:i:s') . '.doc';
		$res = TalentDocument::create($params);
		Queue::push(Task::class, ['data' => ['id' => $res->id], 'action' => 'AiDoc'], 'task');
		writeJson();
	}
	

	
	/**
	 * 获取资料整理配置
	 * @return Json
	 */
	function get_config()
	{
		$rows = Config::where(['extend' => 'chat_gpt'])->select();
		writeJson($rows);
	}
	
	
	/**
	 * 评估
	 * @return Json
	 */
	function assess()
	{
		$TalentAssessModel = new TalentAssess();
		$rows = $TalentAssessModel->withSum('option', 'score')->with(['option'])->where(['pid' => 0])->select();
		writeJson($rows);
	}
	
	/**
	 * 提示详情
	 * @param int $id
	 * @return Json
	 */
	function tip(int $id)
	{
		$class_ids = TalentAssessTip::getFieldById($id, 'class_ids');
		$rows = TalentAssessTipClass::with(['class'])->whereIn('id', $class_ids)->select();
		writeJson($rows);
	}
	
	
	/**
	 * 人才引进-专业团队
	 * @param int $id
	 * @return Json
	 */
	function talent_goods(int $id)
	{
		$res = TalentDataDetail::findOrFail($id);
		if (!in_array($res->type, [2, 3, 4])) {
			writeJson(0, '数据格式错误');
		}
		if (empty($res->goods_ids)) {
			writeJson(0, '暂时未上架商品');
		}
		$rows = TalentGoods::whereIn('id', $res->goods_ids)->filter(function ($data) {
			$price_arr = array_column($data->sku, 'price');
			sort($price_arr);
			$data->min_price = reset($price_arr);
		})->order(['id' => 'desc'])->select();
		writeJson($rows);
	}
	
	/**
	 * 人才引进详情
	 * @param int $id
	 * @return Json
	 */
	function talent_goods_detail(int $id)
	{
		$row = TalentGoods::filter(function ($data) {
			$price_arr = array_column($data->sku, 'price');
			sort($price_arr);
			$min_price = (float)reset($price_arr);
			$max_price = (float)end($price_arr);
			$data->between_price = $min_price . '~' . $max_price;
		})->find($id);
		writeJson($row);
	}
	
	/**
	 * 人才引进-专业团队-创建订单
	 * @param Request $request
	 * @return Json
	 */
	function talent_goods_buy(Request $request)
	{
		$goods_id = $request->post('goods_id/d'); //goods_id sku_id
		$sku_id = $request->post('sku_id/d');
		$goods = TalentGoods::findOrFail($goods_id);
		Db::startTrans();
		try {
			$sku_json = [];
			$amount = 0;
			foreach ($goods->sku as $v) {
				if ($v['id'] ==$sku_id) {
					$amount = $v['price'];
					$sku_json = $v;
					break;
				}
			}
			$order_sn = get_uniqid();
			TalentGoodsOrders::create([
				'users_id'=>$request->users_id,
				'order_sn'=>$order_sn,
				'sku_json'=>$sku_json,
				'goods_id'=>$goods_id,
				'goods_json'=>$goods,
				'amount'=>$amount,
			]);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			writeJson(0, $e->getMessage());
			
		}
		writeJson(1,'ok',['pay_amount'=>$amount,'order_sn'=>$order_sn]);
	}
	
	/**
	 * 专业团队续费
	 * @return void
	 */
	function talent_goods_order_renew(Request $request)
	{
		$id = $request->post('id/d');
		$pay_type = $request->post('pay_type/d');
		$row = TalentGoodsOrders::findOrFail($id);
		if ($row->pay_status!=1){
			writeJson(0,'只能续费进行中的订单');
		}
		$sku = $row->sku_json;
		$order_sn =get_uniqid();
		TalentGoodsOrdersRenew::create([
			'users_id'=>$request->users_id,
			'order_id'=>$id,
			'order_sn'=>$order_sn,
			'pay_type'=>$pay_type,
		]);
		if ($pay_type==3){
			$res = ['apple'=>$sku['ios'],'order_sn'=>$order_sn,'attach'=>'talent_goods_renew'];
		}else{
			try {
				$res = Pay::pay($pay_type, $sku['price'], $order_sn , '团队相助续费', 'talent_goods_renew');
			}catch (Exception $e){
				writeJson(0, $e->getMessage());
			}
		}
		
		writeJson($res);
	}
	
	/**
	 * 人才引进-专业团队-支付
	 * @param Request $request
	 * @return Json
	 */
	function talent_goods_pay(Request $request)
	{
		$order_sn = $request->post('order_sn'); //order_sn pay_type 支付方式:1=微信,2=支付宝
		$pay_type = $request->post('pay_type/d');
		$row = TalentGoodsOrders::where(['order_sn' => $order_sn])->findOrFail();
		$sku = $row->sku_json;
		Db::startTrans();
		try {
			$row->pay_type = $pay_type;
			$row->save();
			
			if ($pay_type==3){
				$res = ['apple'=>$sku['ios'],'order_sn'=> $row->order_sn,'attach'=>'talent_goods_pay'];
			}else{
				$res = Pay::pay($pay_type, $row->amount, $row->order_sn, '团队相助', 'talent_goods_pay');
			}
			Db::commit();
		} catch (\Exception $e) {
			Db::rollback();
			writeJson(0, $e->getMessage());
		}
		writeJson($res);
	}
	
	/**
	 * 获取团队客服列表
	 * @param Request $request
	 * @return void
	 */
	function get_talent_service_list(Request $request)
	{
		$rows = TalentGoodsOrders::where(['users_id'=>$request->users_id])
			->whereIn('pay_status',[1,2])->group('service_user_id')
			->column('service_user_id');
		writeJson($rows);
	}
	
	/**
	 * 订单列表
	 * @param Request $request
	 * @return void
	 */
	function talent_goods_order_list(Request $request)
	{
		$rows = TalentGoodsOrders::with(['service'])
			->where(['users_id'=>$request->users_id])
			->whereIn('pay_status',[1,3])
			->order(['id'=>'desc'])
			->paginate()
			->items();
		writeJson($rows);
	}
	
	/**
	 * 订单详情
	 * @param Request $request
	 * @param int $id
	 * @return void
	 */
	function talent_goods_order_detail(Request $request,int $id)
	{
		$row = TalentGoodsOrders::where(['users_id'=>$request->users_id])
			->findOrFail($id);
		writeJson($row);
	}
	
	/**
	 * 获取客服订单信息
	 * @param Request $request
	 * @param int $to_users_id
	 * @return void
	 */
	function get_service_detail(Request $request,int $to_users_id)
	{
		$row = TalentGoodsOrders::where(['users_id' => $to_users_id,'service_user_id'=>$request->users_id,'pay_status'=>1])->find();
		if (empty($row)) {
			$row = TalentGoodsOrders::where(['users_id' => $request->users_id,'service_user_id'=>$to_users_id,'pay_status'=>1])->find();
		}
		writeJson($row);
	}
	
	/**
	 * 资料整理
	 * @param int $type
	 * @return Json
	 */
	function data_sort(int $type)
	{
		$rows = TalentDataClass::where(['type' => $type])->filter(function ($data) {
			$data->data = TalentData::whereIn('id',$data->data_ids)->select()->append(['detail']);
		})->select();
		
		writeJson($rows);
	}
	
	/**
	 * 留学-排名
	 * @param int $type 排名类型:1=综合排名,2=专业排名
	 * @param int $class type=1  rank_id  type=2 major_id
	 * @param $year
	 * @return Json
	 */
	function ranking(int $type, int $class, $year)
	{
		$rows = TalentSchoolRank::with(['school'])->where(['type' => $type, 'year' => $year])->when(!empty($type), function (Query $query) use ($class, $type) {
			if ($type == 1) {
				$query->where(['rank_id' => $class]);
			} else {
				$query->where(['major_id' => $class]);
			}
		})->order(['is_ranking' => 'desc', 'ranking' => 'asc'])->paginate()->items();
		writeJson($rows);
	}
	
	/**
	 * 学校详情
	 * @param int $school_id
	 * @return Json

	 */
	function ranking_detail(int $school_id)
	{
		$row = TalentSchool::with(['active'])->filter(function ($data) use ($school_id) {
			
			$data->compress = TalentSchoolRank::field('year')->filter(function ($data) use ($school_id) {
				$data->compress = TalentSchoolRank::with(['rank'])->where(['school_id' => $school_id, 'type' => 1, 'year' => $data->year])->select();
				
			})->where(['school_id' => $school_id, 'type' => 1])->order(['year' => 'desc'])->group('year')->select();
			
			$data->major = TalentSchoolRank::field('year')->filter(function ($data) use ($school_id) {
				
				$data->major = TalentSchoolRank::with(['major'])->where(['school_id' => $school_id, 'type' => 2, 'year' => $data->year])->select();
			})->where(['school_id' => $school_id, 'type' => 2])->order(['year' => 'desc'])->group('year')->select();
		})->findOrFail($school_id);
		
		writeJson($row);
	}
	
	/**
	 * 申请项目详情
	 * @param int $id
	 * @return Json

	 */
	function ranking_active_detail(int $id)
	{
		$row = TalentSchoolClass::with(['school'])
			->find($id);
		writeJson($row);
	}
	
	/**
	 * 申请须知
	 * @return Json

	 */
	function talent_rule()
	{
		$rows = Config::where(['group' => 'talent_rule'])
			->select();
		writeJson($rows);
	}
	
	/**
	 * 留学-专业分类
	 * @return Json

	 */
	function major()
	{
		$rows = TalentSchoolMajor::with(['class'])
			->where(['pid' => 0])
			->select();
		writeJson($rows);
	}
	
	/**
	 * 留学-排名分类
	 * @return Json

	 */
	function compress()
	{
		$rows = TalentSchoolCompress::select();
		writeJson($rows);
	}
	
	/**
	 * 年份
	 * @return Json
	 */
	function year(int $type, int $class)
	{
		$rows = TalentSchoolRank::where(['type' => $type])
			->when(!empty($type), function (Query $query) use ($type, $class) {
				if ($type == 1) {
					$query->where(['rank_id' => $class]);
				} else {
					$query->where(['major_id' => $class]);
				}
			})
			->order(['year' => 'desc'])
			->group(['year'])
			->column('year');
		writeJson($rows);
	}
	
	/**
	 * 批量删除
	 * @param Request $request
	 * @return Json
	 */
	public function delete(Request $request)
	{
		$ids = $request->post('ids');
		Talent::whereIn('id', $ids)
			->where(['users_id' => $request->users_id])
			->select()
			->delete();
		writeJson();
	}
}
